#include <iostream>
#include "Sock.hpp"
#include <unistd.h>
#include "Pro_to_col.hpp"
using namespace ser_and_dser;
static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << "serverip serverport\n";
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string server_ip = argv[1];
    int16_t server_port = atoi(argv[2]);
    Sock sock;
    int sockfd = sock.Socket();
    if (!sock.Connect(sockfd, server_ip, server_port))
    {
        std::cerr << "Connet error" << std::endl;
        exit(2);
    }
    // 任务
    bool quit = false;
    std::string buffer;
    // int count = 0;
    while (!quit)
    {
        Request req;
        std::cout << "Please Enter # ";
        std::cin >> req._x >> req._op >> req._y;
        // 序列化
        std::string s = req.Serialize();
        s = Encode(s);
        Send(sockfd, s);
        while (true)
        {
            bool r = Recv(sockfd, &buffer);
            if (!r)
            {
                quit = true;
                break;
            }
            std::string package = Decode(buffer);
            if (package.empty())
                continue;
            Response resp;
            std::string err;
            resp.Deserlize(package);
            switch (resp._flag)
            {
            case 1:
                err = "除0错误";
                break;
            case 2:
                err = "模0错误";
                break;
            case 3:
                err = "非法操作";
                break;
            default:
                std::cout << req._x << req._op << req._y << " = " << resp._res << " [success]" << std::endl;
                break;
            }
            if(!err.empty()) std::cerr << err << std::endl;
            break;
        }
    }
    close(sockfd);
    return 0;
}